//
//  PhotoAlbumPreviewController.swift
//  EasePods
//
//  Created by 易先生 on 2024/5/22.
//

import UIKit
import RxSwift
import RxCocoa
import MoyoungLib
import Photos

class PhotoAlbumPreviewController: ViewController {

    public var PhotosRelay: BehaviorRelay = BehaviorRelay<[PHAsset]>(value: [])
    
    private let targetSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
    
    public var selectIndex: Int = 0
    
    private var toolViewsTimer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

    }
    
    override func makeUI() {
        super.makeUI()
        
        self.view.backgroundColor = .black
        self.view.addSubview(collectionView)
        self.view.addSubview(topToolView)
        self.view.addSubview(bottomToolView)
        
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        topToolView.snp.makeConstraints { make in
            make.top.equalTo(collectionView.snp.top)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(kNavHeight)
        }
        
        bottomToolView.snp.makeConstraints { make in
            make.bottom.leading.trailing.equalToSuperview()
        }
        
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if selectIndex < PhotosRelay.value.count {
            collectionView.scrollToItem(at: IndexPath(row: selectIndex, section: 0), at: .centeredHorizontally, animated: false)
        }
        
        // 设置计时器，5秒后自动隐藏工具视图
        startToolViewsTimer()
    }
    
    override func bindViewModel() {
        super.bindViewModel()
        
        topToolView.leftButton.rx.tap.subscribe(onNext: { [weak self] _ in
            guard let `self` = self else { return }
            self.dismiss(animated: true, completion: nil)
        }).disposed(by: rx.disposeBag)
        
        bottomToolView.moreButton.rx.tap.subscribe(onNext: { [weak self] _ in
            guard let `self` = self else { return }
            self.dismiss(animated: true, completion: nil)
        }).disposed(by: rx.disposeBag)
        
        bottomToolView.shareButton.rx.tap.subscribe(onNext: { [weak self] _ in
            guard let `self` = self else { return }
            
            if self.selectIndex < PhotosRelay.value.count {
                
                let asset = PhotosRelay.value[self.selectIndex]
                let imageManager = PHImageManager.default()
                let requestOptions = PHImageRequestOptions()
                requestOptions.isSynchronous = false
                requestOptions.deliveryMode = .highQualityFormat
                
                imageManager.requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: requestOptions) { image, info in
                    if let image = image {
                        let activityViewController = UIActivityViewController(activityItems: [image as Any], applicationActivities: nil)
                        self.present(activityViewController, animated: true, completion: nil)
                    }
                }
            }
            
        }).disposed(by: rx.disposeBag)
        
        PhotosRelay.bind(to: collectionView.rx.items(cellIdentifier: PhotoAlbumCollectionViewCell.reuseIdentifier, cellType: PhotoAlbumCollectionViewCell.self)) { i, item, cell in
            cell.bind(to: item, isPreview: true)
        }.disposed(by: rx.disposeBag)
        
        collectionView.rx.itemSelected.subscribe(onNext: { [weak self] _ in
            guard let self = self else { return }
            self.toggleToolViewsVisibility()
        }).disposed(by: rx.disposeBag)
        
        collectionView.rx.setDelegate(self).disposed(by: rx.disposeBag)
    }
    
    private func toggleToolViewsVisibility() {
        
        let newAlpha: CGFloat = topToolView.alpha == 1.0 ? 0.0 : 1.0
        UIView.animate(withDuration: 0.5) {
            self.topToolView.alpha = newAlpha
            self.bottomToolView.alpha = newAlpha
        }
        startToolViewsTimer()
    }
    
    private func startToolViewsTimer() {
        toolViewsTimer?.invalidate() // 取消之前的计时器
        toolViewsTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: false) { [weak self] _ in
            self?.hideToolViews()
        }
    }
    
    private func hideToolViews() {
        UIView.animate(withDuration: 0.5) {
            self.topToolView.alpha = 0.0
            self.bottomToolView.alpha = 0.0
        }
    }
    
    private lazy var topToolView: PhotoAlbumTopToolView = {
        let view = PhotoAlbumTopToolView()
        view.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
        return view
    }()
    
    private lazy var bottomToolView: PhotoAlbumBottomToolView = {
        let view = PhotoAlbumBottomToolView()
        view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
        return view
    }()
    
    
        
    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayoutView)
        collectionView.backgroundColor = .black
        collectionView.register(PhotoAlbumCollectionViewCell.self, forCellWithReuseIdentifier: PhotoAlbumCollectionViewCell.reuseIdentifier)
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.bounces = true
        collectionView.isPagingEnabled = true
        return collectionView
    }()
    
    private lazy var flowLayoutView: UICollectionViewFlowLayout = {
        let flowLayoutView = UICollectionViewFlowLayout()
        flowLayoutView.scrollDirection = .horizontal
        flowLayoutView.minimumLineSpacing = 0
        flowLayoutView.minimumLineSpacing = 0
        flowLayoutView.itemSize = targetSize
        return flowLayoutView
    }()
    
}

extension PhotoAlbumPreviewController: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let index = scrollView.contentOffset.x/UIScreen.main.bounds.width
        self.selectIndex = Int(index)
    }
}

class PhotoAlbumTopToolView: View {
    
    override func makeUI() {
        super.makeUI()
        
        self.addSubview(leftButton)
        leftButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(12)
            make.size.equalTo(CGSize(width: 39, height: 44))
            make.bottom.equalToSuperview()
        }
    }
    
    public lazy var leftButton: UIButton = {
        let button = UIButton()
        button.setImage(R.image.ic_common_nav_back(), for: .normal)
        return button
    }()
}

class PhotoAlbumBottomToolView: View {
    
    override func makeUI() {
        super.makeUI()
        
        self.addSubview(moreButton)
        self.addSubview(shareButton)

        moreButton.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.leading.equalToSuperview().offset(10)
            make.size.equalTo(CGSize(width: 44, height: 44))
            make.centerY.equalToSuperview()
        }
        
        shareButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-10)
            make.size.equalTo(CGSize(width: 44, height: 44))
            make.centerY.equalToSuperview()
        }
    }
    
    public lazy var moreButton: UIButton = {
        let button = UIButton()
        button.setImage(R.image.ic_photo_more(), for: .normal)
        return button
    }()
    
    public lazy var shareButton: UIButton = {
        let button = UIButton()
        button.setImage(R.image.ic_photo_share(), for: .normal)
        return button
    }()
}

